/*
 * This product includes software developed by IBM Corporation (www.ibm.com).
 * All use and distribution of the IBM developed software is subject to Version 2.0
 * of the Apache License (http://www.apache.org/licenses/LICENSE-2.0).
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

using AppScan.Scan.Data;
using AppScan;
using AppScan.Scan;
using AppScan.Events;
using AppScan.Extensions;
using AppScan.Scan.Events;

namespace Test_Positive
{
     public class Test_Positive : IExtensionLogic
     {
         

            #region Initialization
            public void Load(IAppScan appscan, IAppScanGui appScanGui, string extensionDir)
            {
                  InitGuiHooks();
                  RegisterGuiHooks(appScanGui);
                  appscan_rules = appscan.Version.RulesVersion;
            }

            private void InitGuiHooks()
            {
                  extMenuItems = CreateMenuItems();  // Create a (Tools->Extension) menu entry collection
                  IssueMenuItems = CreateIssueContextMenuItems(); // Create a context-menu entry collection
                  
            }

            private void RegisterGuiHooks(IAppScanGui appScanGui)
            {
                  foreach (IMenuItem<EventArgs> item in extMenuItems)
                        appScanGui.ExtensionsMenu.Add(item);

                  foreach (IMenuItem<IssuesEventArgs> item in IssueMenuItems)
                        appScanGui.IssueContextMenu.Add(item);
                  
            }

 
            #endregion Initialization

            #region GUI itmes construction
            private ICollection<IMenuItem<EventArgs>> CreateMenuItems()
            {
                  mainExtMenuItem = new MenuItem<EventArgs>("Send to Test Positive - Information", DelegateEmpty);
                  List<IMenuItem<EventArgs>> items = new List<IMenuItem<EventArgs>>();
                  items.Add(mainExtMenuItem);
                  return items;

            }
            private ICollection<IMenuItem<IssuesEventArgs>> CreateIssueContextMenuItems()
            {
                  mainIssuesExtMenuItem = new MenuItem<IssuesEventArgs>("Send to Test Positive", DelegateIssue1);
                  List<IMenuItem<IssuesEventArgs>> items = new List<IMenuItem<IssuesEventArgs>>();
                  items.Add(mainIssuesExtMenuItem);
                  return items;
            }
            #endregion GUI itmes construction


            #region delegates
            private static void DelegateEmpty(EventArgs args)
            {
                 MessageBox.Show("Send to Test Positive\n"+
                "The Send-to-Test-Positive extension interfaces AppScan Desktop with\n"+
                "the Test Positive vulnerability viewer and analyzer. Use this tool to\n"+
                "examine suspected false positives or to export vulnerabilities from AppScan\n"+
                "and send them to your colleagues.\n\n"+
                "To export a specific vulnerability right click on the vulnerable item and choose\n"+
                "Send to Test Positive.", "Send to test Positive",
            MessageBoxButtons.OK, MessageBoxIcon.Information ,
            MessageBoxDefaultButton.Button1);     
            }


            private void DelegateIssue1(IssuesEventArgs args)
            {
                  DoDelegateIssue(1, args.issues);
            }


            private static void DoDelegateIssue(int num, ICollection<IIssue> issues)
            {
                  if (issues == null) return;
                  if (issues.Count>1)
                  {
                      MessageBox.Show("You have selected more than one issue. Please expand the\n"+
                          "tree and select a specific item."
                          , "Send to test Positive",
                        MessageBoxButtons.OK, MessageBoxIcon.Error, 
                        MessageBoxDefaultButton.Button1);
                      return;
                  }
                  if (issues.Count == 1) {
                      IEnumerator<IIssue> i_enumerator=issues.GetEnumerator();
                      i_enumerator.MoveNext();
                      IEnumerator<ITest> v_enumerator=
                          i_enumerator.Current.Variants.GetEnumerator();
                      v_enumerator.MoveNext();
                      IVariant var=(IVariant)v_enumerator.Current;
                      string temp_path = Environment.GetEnvironmentVariable("temp");
                      string user_profile = Environment.GetEnvironmentVariable("userprofile");

                      try
                      {
                          StreamWriter f = new StreamWriter(temp_path + "\\testp_export.txt");
                          StringReader s;
                          f.WriteLine("AppScan Rules: "+appscan_rules);
                          f.WriteLine("Issue Name: " + var.IssueType.Name +
                              " \"" + var.RuleName + "\" ");
                          f.WriteLine("URL: " + var.OriginalRequest.Uri.AbsoluteUri);
                          f.WriteLine("ID: " + Convert.ToString( var.Id));
                          f.WriteLine("Reasoning: " + var.Reasoning);
                          if (var.ValidationLocations.Count > 0)
                          {
                              IEnumerator<AppScan.Scan.Results.Issue.IValidationLocation> validations = var.ValidationLocations.GetEnumerator();
                              validations.MoveNext();
                              string validation = var.TestRequestResponse.Substring(
                                validations.Current.Location,
                                validations.Current.Length);

                              f.WriteLine("Validation: \n1. \'" + validation + "\'" +
                                  " (location:" + Convert.ToString(validations.Current.Location) +
                                  ",length:" + Convert.ToString(validations.Current.Length) + ")");
                          }
                          f.WriteLine();
                          f.WriteLine("Original Request/Response ");
                          f.WriteLine("-------------------------");

                          s = new StringReader(var.OriginalRequest.LogicalResponse);
                          while (s.Peek() >= 0) f.WriteLine(s.ReadLine());
                          f.WriteLine();
                          
                          f.WriteLine("Test Request/Response ");
                          f.WriteLine("-------------------------");
                          s = new StringReader(var.TestRequestResponse);
                          while (s.Peek() >= 0) f.WriteLine(s.ReadLine());
                          f.Close();
                          System.Diagnostics.Process P= new System.Diagnostics.Process();
                          if (File.Exists(user_profile +
                              "\\Application Data\\IBM\\Rational AppScan\\Extensions\\" +
                          "Send-to-Test-Positive\\test_positive.exe"))
                              P.StartInfo.FileName = user_profile +
                                  "\\Application Data\\IBM\\Rational AppScan\\Extensions\\" +
                              "Send-to-Test-Positive\\test_positive.exe";
                          else
                              P.StartInfo.FileName = user_profile +
                              "\\Application Data\\IBM\\Rational AppScan\\Extensions\\" +
                          "Send-to-Test-Positive\\test_positive.exe";
                          P.StartInfo.Arguments = temp_path + "\\testp_export.txt";
                          P.Start();
                      }
                      catch (Exception ex)
                      {
                          MessageBox.Show(ex.Message
                            , "Send to test Positive",
                               MessageBoxButtons.OK, MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1);
                      }

                  }  

            }


            #endregion delegates

 

            #region data members

 

            IMenuItem<EventArgs> mainExtMenuItem;

            IMenuItem<IssuesEventArgs> mainIssuesExtMenuItem;

 

            ICollection<IMenuItem<EventArgs>> extMenuItems;

            ICollection<IMenuItem<IssuesEventArgs>> IssueMenuItems;

            static string appscan_rules="";

            const string messageTitle = "Send to test Positive";

            const string messagePrefix = "";

 

            #endregion data members

 

            #region other

          
            public ExtensionVersionInfo GetUpdateData(Edition targetApp, System.Version targetAppVersion)
            {
                  return null;
            }

            #endregion other

      }

}

 

